package com.kun.service.impl;

import com.kun.entity.Book;
import com.kun.entity.BookExample;
import com.kun.entity.BookExample.Criteria;
import com.kun.entity.message.response.Article;
import com.kun.entity.message.response.NewsMessage;
import com.kun.entity.message.response.TextMessage;
import com.kun.mapper.cluster.custom.BookMapperRCustom;
import com.kun.service.WechatService;
import com.kun.util.wechat.MessageUtil;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description: 
 * @author: KM
 * 2018年4月14日 下午5:32:38
 */
@Service
public class WechatServiceImpl implements WechatService {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	
	@Autowired
	private BookMapperRCustom bookMapperRCustom;
	
	/**
     * @description: 处理微信发来的请求（包括事件的推送）
     * @param request
     * @return
     */
	@SuppressWarnings("static-access")
	@Override
	public String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);

			// 创建图文消息
			NewsMessage newsMessage = new NewsMessage();
			newsMessage.setToUserName(fromUserName);
			newsMessage.setFromUserName(toUserName);
			newsMessage.setCreateTime(new Date().getTime());
			newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
			newsMessage.setFuncFlag(0);

			List<Article> articleList = new ArrayList<Article>();
			// 接收文本消息内容
			String content = requestMap.get("Content");
			//点击菜单id
            String EventKey =requestMap.get("EventKey");
			// 自动回复文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {

				// 如果用户发送表情，则回复同样表情。
				if (isQqFace(content)) {
					respContent = content;
					textMessage.setContent(respContent);
					// 将文本消息对象转换成xml字符串
					respMessage = MessageUtil.textMessageToXml(textMessage);
				} else {
					// 回复固定消息
					switch (content) {
					
					case "1": {
						StringBuffer buffer = new StringBuffer();
						buffer.append("您好，我是客服小艺(#^.^#)，请回复暗号选择服务：").append("\n\n");
						buffer.append("b 可查看平台图书").append("\n");
						buffer.append("回复“1”显示此帮助菜单");
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					case "b": {
						StringBuffer buffer = new StringBuffer();
						buffer.append("回复b1 查看文学类图书").append("\n\n");
						buffer.append("回复b2 查看外语类图书").append("\n\n");
						buffer.append("回复b3 查看经济类图书").append("\n\n");
						buffer.append("回复b4 查看管理类图书").append("\n\n");
						buffer.append("回复b5 查看计算机类图书").append("\n\n");
						buffer.append("回复b6 查看科学类图书");
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					case "b1": {
						BookExample bex = new BookExample();
						Criteria criteria = bex.createCriteria();
						criteria.andTypeidEqualTo(1);
						int allRecord = bookMapperRCustom.countByExample(bex);
						List<Book> bookList = bookMapperRCustom.selectByExample(bex);
						
						StringBuffer buffer = new StringBuffer();
						buffer.append("--共有").append(allRecord).append("种文学类图书--").append("\n\n");
						for (Book book : bookList) {
							buffer.append("书名：").append(book.getBookname()).append("  作者：").append(book.getBookauthor()).append("\n").append("出版社：").append(book.getBookpress()).append("\n").append("库存：").append(book.getBookamount()).append("\n\n");
						}
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					case "b2": {
						BookExample bex = new BookExample();
						Criteria criteria = bex.createCriteria();
						criteria.andTypeidEqualTo(2);
						int allRecord = bookMapperRCustom.countByExample(bex);
						List<Book> bookList = bookMapperRCustom.selectByExample(bex);
						
						StringBuffer buffer = new StringBuffer();
						buffer.append("--共有").append(allRecord).append("种外语类图书--").append("\n\n");
						for (Book book : bookList) {
							buffer.append("书名：").append(book.getBookname()).append("  作者：").append(book.getBookauthor()).append("\n").append("出版社：").append(book.getBookpress()).append("\n").append("库存：").append(book.getBookamount()).append("\n\n");
						}
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					case "b3": {
						BookExample bex = new BookExample();
						Criteria criteria = bex.createCriteria();
						criteria.andTypeidEqualTo(3);
						int allRecord = bookMapperRCustom.countByExample(bex);
						List<Book> bookList = bookMapperRCustom.selectByExample(bex);
						
						StringBuffer buffer = new StringBuffer();
						buffer.append("--共有").append(allRecord).append("种经济学类图书--").append("\n\n");
						for (Book book : bookList) {
							buffer.append("书名：").append(book.getBookname()).append("  作者：").append(book.getBookauthor()).append("\n").append("出版社：").append(book.getBookpress()).append("\n").append("库存：").append(book.getBookamount()).append("\n\n");
						}
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					case "b4": {
						BookExample bex = new BookExample();
						Criteria criteria = bex.createCriteria();
						criteria.andTypeidEqualTo(4);
						int allRecord = bookMapperRCustom.countByExample(bex);
						List<Book> bookList = bookMapperRCustom.selectByExample(bex);
						
						StringBuffer buffer = new StringBuffer();
						buffer.append("--共有").append(allRecord).append("种管理类图书--").append("\n\n");
						for (Book book : bookList) {
							buffer.append("书名：").append(book.getBookname()).append("  作者：").append(book.getBookauthor()).append("\n").append("出版社：").append(book.getBookpress()).append("\n").append("库存：").append(book.getBookamount()).append("\n\n");
						}
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					case "b5": {
						BookExample bex = new BookExample();
						Criteria criteria = bex.createCriteria();
						criteria.andTypeidEqualTo(5);
						int allRecord = bookMapperRCustom.countByExample(bex);
						List<Book> bookList = bookMapperRCustom.selectByExample(bex);
						
						StringBuffer buffer = new StringBuffer();
						buffer.append("--共有").append(allRecord).append("种计算机类图书--").append("\n\n");
						for (Book book : bookList) {
							buffer.append("书名：").append(book.getBookname()).append("  作者：").append(book.getBookauthor()).append("\n").append("出版社：").append(book.getBookpress()).append("\n").append("库存：").append(book.getBookamount()).append("\n\n");
						}
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					case "b6": {
						BookExample bex = new BookExample();
						Criteria criteria = bex.createCriteria();
						criteria.andTypeidEqualTo(6);
						int allRecord = bookMapperRCustom.countByExample(bex);
						List<Book> bookList = bookMapperRCustom.selectByExample(bex);
						
						StringBuffer buffer = new StringBuffer();
						buffer.append("--共有").append(allRecord).append("种科学类图书--").append("\n\n");
						for (Book book : bookList) {
							buffer.append("书名：").append(book.getBookname()).append("  作者：").append(book.getBookauthor()).append("\n").append("出版社：").append(book.getBookpress()).append("\n").append("库存：").append(book.getBookamount()).append("\n\n");
						}
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}

					case "sb": {
						StringBuffer buffer = new StringBuffer();
						buffer.append("您好,您还欠本平台十万本书，打算什么时候还呢？").append("\n\n");
						respContent = String.valueOf(buffer);
						textMessage.setContent(respContent);
						respMessage = MessageUtil.textMessageToXml(textMessage);
						break;
					}
					
					default: {
						respContent = "（这是里面的）很抱歉，现在小艺暂时无法提供此功能给您使用。\n\n回复“1”显示帮助信息";
						textMessage.setContent(respContent);
						// 将文本消息对象转换成xml字符串
						respMessage = MessageUtil.textMessageToXml(textMessage);
					}
					}
				}
			}
			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息！";
				textMessage.setContent(respContent);
				// 将文本消息对象转换成xml字符串
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			// 地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！";
				textMessage.setContent(respContent);
				// 将文本消息对象转换成xml字符串
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
				textMessage.setContent(respContent);
				// 将文本消息对象转换成xml字符串
				respMessage = MessageUtil.textMessageToXml(textMessage);

			}
			// 音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！";
				textMessage.setContent(respContent);
				// 将文本消息对象转换成xml字符串
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
			
			
			// 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件类型
                String eventType =requestMap.get("Event");
                // 自定义菜单点击事件
                 if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
                    switch (EventKey){
	                    case "1":{
	                    	StringBuffer buffer = new StringBuffer();
							buffer.append("回复b1 查看文学类图书").append("\n\n");
							buffer.append("回复b2 查看外语类图书").append("\n\n");
							buffer.append("回复b3 查看经济类图书").append("\n\n");
							buffer.append("回复b4 查看管理类图书").append("\n\n");
							buffer.append("回复b5 查看计算机类图书").append("\n\n");
							buffer.append("回复b6 查看科学类图书");
							respContent = String.valueOf(buffer);
	                        break;
	                    }
                        case "11":{
                            respContent = "慈善书库1";
                            break;
                        }
                        case "12":{
                            respContent = "慈善书库2";
                            break;
                        }
                        case "21":{
                            respContent = "个人信息";
                            break;
                        }
                        case "22":{
                            respContent = "实名认证";
                            break;
                        }
                        case "23":{
                        	Date date=new Date();//取时间
                        	Calendar calendar = new GregorianCalendar();
                        	calendar.setTime(date);
                        	calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
                        	date=calendar.getTime(); //这个时间就是日期往后推一天的结果 
                        	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        	String dateString = formatter.format(date);
                            respContent = "你还欠本平台十万本图书，截止归还日期为" + dateString + "\n" + "请尽快交还！否则...";
                            break;
                        }

                        default:{
                            logger.error("开发者反馈：EventKey值没找到，它是:"+EventKey);
                            respContent= "很抱歉，此按键功能正在升级无法使用";
                        }
                    }
                    textMessage.setContent(respContent);
                    // 将文本消息对象转换成xml字符串
                    respMessage = MessageUtil.textMessageToXml(textMessage);
                }
                else if(eventType.equals(MessageUtil.EVENT_TYPE_VIEW)){
                    // 对于点击菜单转网页暂时不做推送
                }
                 
                // 订阅
                else if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    //测试单图文回复
                    Article article = new Article();
                    article.setTitle("感谢您的关注！");
                    // 图文消息中可以使用QQ表情、符号表情
                    article.setDescription("本平台为慈善借阅平台");
                    // 图片
                    article.setPicUrl("https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com/sys/8572479_204027251000_2.jpg");
                    article.setUrl("http://www.baidu.com");
                    articleList.add(article);
                    newsMessage.setArticleCount(articleList.size());
                    newsMessage.setArticles(articleList);
                    respMessage = MessageUtil.newsMessageToXml(newsMessage);
                }
                else if(eventType.equals(MessageUtil.EVENT_TYPE_SCAN)){
                    //测试单图文回复
                    Article article = new Article();
                    article.setTitle("这是已关注用户扫描二维码弹到的界面");
                    // 图文消息中可以使用QQ表情、符号表情
                    article.setDescription("本平台为慈善借阅平台");
                    // 将图片置为空
                    article.setPicUrl("https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com/sys/8572479_204027251000_2.jpg");
                    article.setUrl("http://www.baidu.com");
                    articleList.add(article);
                    newsMessage.setArticleCount(articleList.size());
                    newsMessage.setArticles(articleList);
                    respMessage = MessageUtil.newsMessageToXml(newsMessage);
                }
                // 取消订阅
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    // TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
                }
            
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

	
	/**
	 * 判断是否是QQ表情
	 *
	 * @param content
	 * @return
	 */
	public static boolean isQqFace(String content) {
	        boolean result = false;
	        // 判断QQ表情的正则表达式
	        String qqfaceRegex = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O|/::\\(|/::\\+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>";
	        Pattern p = Pattern.compile(qqfaceRegex);
	        Matcher m = p.matcher(content);
	        if (m.matches()){
	        	result = true;
	        }
	        return result;
    }
	
	
}

